<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/12
 * Time: 8:44
 */

namespace core;


class Config
{
    protected static $instance;
    private static $configs;

    public function __construct()
    {
        $dir = '../configs';
        if (is_null(static::$configs)) {
            static::$configs = $this->setConfigsByDir($dir);
        }
    }

    /**
     * 获取单例
     * @return Config
     */
    public static function getInstance()
    {
        if (is_null(static::$instance)){
            static::$instance = new static();
        }
        return static::$instance;
    }

    public function getConfig($name = '')
    {
        if (!$name){
            return static::$configs;
        }
        if (strpos($name,'.')){
            $arr = explode('.',$name);
            $res = static::$configs;
            for ($i = 0 ; $i < count($arr) ; $i ++ ){
                if (isset($res[$arr[$i]])){
                    $res = $res[$arr[$i]];
                }else{
                    return false;
                }
            }
        }else{
            return isset(static::$configs[$name]) ? static::$configs[$name] : false;
        }
        return $res;
    }

    public function setConfigsByDir($dir)
    {
        $handle = opendir($dir);
        while (($fl = readdir($handle)) !== false) {
            if ($fl == '.') continue;
            if ($fl == '..') continue;
            if (is_dir($dir.DIRECTORY_SEPARATOR.$fl)) {
                $configs[$fl] = $this->setConfigsByDir($dir . DIRECTORY_SEPARATOR . $fl);
                continue;
            }
            $pathInfo = pathinfo($fl);
            if ($pathInfo['extension'] == 'php') {
                $configs[$pathInfo['filename']] = include_once $dir . DIRECTORY_SEPARATOR . $pathInfo['basename'];
            }
        }
        return $configs;
    }
}